import localforage from 'localforage'
import axios from 'axios'

export function addZero(num: number) {
  return num < 10 ? `0${num}` : num
}

export function formatTime(time: string) {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = addZero(date.getMonth() + 1)
  const day = addZero(date.getDate())
  const hour = addZero(date.getHours())
  const minite = addZero(date.getMinutes())
  const second = addZero(date.getSeconds())
  return `${year}-${month}-${day} ${hour}:${minite}:${second}`
}

export function getNow() {
  const arr = [ '日', '一', '二', '三', '四', '五', '六' ]
  const date = new Date()
  const year = date.getFullYear()
  const month = addZero(date.getMonth() + 1)
  const day = addZero(date.getDate())
  const hour = addZero(date.getHours())
  const minite = addZero(date.getMinutes())
  const second = addZero(date.getSeconds())
  return `周${arr[date.getDay()]} ${year}-${month}-${day} ${hour}:${minite}:${second}`
}
export function filterPermission(permissions) {
  const res: any[] = []
  permissions.forEach(item => {
    if (item.name === 'AbpIdentity' || item.name === 'SamsinoYard'){
      item.permissions.forEach(permission => {
        if (permission.isGranted){
          res.push(permission)
        }
      })
    }
  })
  return res
}

// 获取本地缓存中的图片，创建img元素展示
export async function addImg(imgName, container) {
  const res:any = await localforage.getItem(imgName)
  const URL = window.URL || window.webkitURL
  // console.log( URL.createObjectURL());
  const url = URL.createObjectURL(res)
  const img:any = document.createElement('img')
  img.src = url
  img.style = 'width:100%;'
  const parentDom = document.getElementById(container) as HTMLElement
  if (parentDom.childNodes.length > 0) {
    parentDom.removeChild(parentDom.childNodes[0])
    parentDom.append(img)
  } else {
    parentDom.append(img)
  }

}

export function localForageImg(imgUrl, imgName) {
  return new Promise(reslove => {
    axios({
      url: './' + imgUrl,
      method: 'get',
      responseType: 'blob'
    }).then(res => {
      localforage.setItem(imgName, res.data).then(() => {
        reslove('success')
      })
    })

  })
}